var imgFile,imgFile2;
var parentIds=0;
$(function () {
    getTree();
    /*上架时间*/
    $("#schduleDateStart").datetimepicker({
        timeFormat: "HH:mm:ss",
        dateFormat: "yy-mm-dd",
        onSelect:function(dateText,inst){$("#schduleDateEnd").datepicker("option","minDate",dateText);}
    });
    //下架时间
    $("#schduleDateEnd").datetimepicker({
        timeFormat: "HH:mm:ss",
        dateFormat: "yy-mm-dd",
        onSelect:function(dateText,inst){$("#schduleDateStart").datepicker("option","maxDate",dateText);}
    });
});
/*重置*/
function resetClick(){
    $(".dis-inebl input").val("");
    $("#userState option:selected").text("全部");
    $("#type option:selected").text("全部");
    getUserList();
}
/*获取树形菜单*/
function getTree(){
    ym.ajax({
        url : "/shop/cat/get",
        type : "post",
        param:{
            "parentId":0
        },
        success : function(data) {
            var zNodes=data.obj;
            //设置
            var setting = {view:{dblClickExpand: false,selectedMulti:false,nameIsHTML:true},data:{simpleData:{enable:true}},callback:{onClick:onClickTree}};
            $.fn.zTree.init($("#preResourcesTree"), setting, zNodes);

        }
    })
    getUserList();
}
function onClickTree(e, treeId, treeNode) {
    parentIds=0;
    var zTree = $.fn.zTree.getZTreeObj("preResourcesTree"),
        nodes = zTree.getSelectedNodes(),v ="",n ="",p="";
    for (var i=0, l=nodes.length; i<l; i++) {
        v += nodes[i].name + ",";//获取name值
        n += nodes[i].id + ",";//获取id值
        var pathNodes=nodes[i].getPath();
        for(var y=0;y<pathNodes.length;y++){
            p+=pathNodes[y].name+"/";//获取path/name值
        }
    }
    if (v.length > 0 ) v = v.substring(0, v.length-1);
    if (n.length > 0 ) n = n.substring(0, n.length-1);
    if (p.length > 0 ) p = p.substring(0, p.length-1);
    $("#preResources").prop("value",p);
    $("#auForm input[name$='parentId']").prop("value",n);
    parentIds=n;
    //因为单选选择后直接关闭，如果多选请另外写关闭方法
    hidePreResources();
}
var preisShow=false;//窗口是否显示
function showPreResources() {
    if(preisShow){
        hidePreResources();
    }else{
        var obj = $("#preResources");
        var offpos = $("#preResources").position();
        $("#preResourcesContent").css({left:offpos.left+"px",top:offpos.top+obj.heith+ "px"}).slideDown("fast");
        preisShow=true;
    }
}
function hidePreResources(){
    $("#preResourcesContent").fadeOut("fast");
    preisShow=false;
}
/*查询*/
function getUserList(init){
    JY.Model.loading();
	$("#ticktTable tbody").html("");
    var pageNum=$("#baseForm .pageNum").val();
    var pageSize=$("#baseForm .pageSize").val();
    var userState=$("#userState option:selected").val();
    var type=$("#type option:selected").val();
    if($("#userState option:selected").text()=="全部"){
        userState="";
    }
    if($("#type option:selected").text()=="全部"){
        type="";
    }
    ym.ajax({
		url : "/shop/product/conditionalQuery",
		type : "post",
        param:{
            "pageNum":pageNum,
            "pageSize":pageSize,
            "state":userState,
            "type":type,
		},
		jsonType : "jsonp",
		success : function(data) {
            var data=data instanceof Object ? data : JSON.parse(data);
            console.log(data);
            var html="";
            var list=data.obj;
            var results=list.list;
            var pageNum=list.pageNum,
                pageSize=list.pageSize,
                totalRecord=list.totalRecord;
           if(results!=null&&results.length>0){
                var leng=(pageNum-1)*pageSize;//计算序号
                for(var i = 0;i<results.length;i++){
                    var l=results[i];
                    var jsonL=JSON.stringify(l);
                    html+="<tr class='tr_color'>";
                    html+="<td class='center ver-m'><label><input type='checkbox' name='ids' value='"+jsonL+"' class='ace' /> <span class='lbl'></span></label></td>";
                    html+="<td class='center'>"+l.productName+"</td>";
                    var productPrice=(l.productPrice*0.01).toFixed(2);
                    html+="<td class='center'>"+productPrice+"</td>";
                    html+="<td class='center'>"+l.productPoint+"</td>";
                    html+="<td class='center'>"+l.name+"</td>";
                    html+="<td class='center'>"+l.productNumber+"</td>";
                    if(l.productType==1){
                        html+="<td class='center'>混合购买</td>";
                    }else if(l.productType==2){
                        html+="<td class='center'>积分兑换</td>";
                    }
                    if(l.onTimeString==null||l.onTimeString==undefined||l.onTimeString==""){
                        l.onTimeString="暂无"
                    }
                    html+="<td class='center'>"+l.onTimeString+"</td>";
                    if(l.offTimeString==null||l.offTimeString==undefined||l.offTimeString==""){
                        l.offTimeString="暂无"
                    }
                    html+="<td class='center'>"+l.offTimeString+"</td>";
                    if(l.state==1){
                        html+="<td class='center'>有效</td>";
                    }else if(l.state==0){
                        html+="<td class='center'>失效</td>";
                    }
                    html+="</tr>";
                }
                $("#ticktTable tbody").append(html);
                JY.Page.setPage("baseForm","pageing",pageSize,pageNum,totalRecord,"getUserList");
            }else{
                html+="<tr><td colspan='10' class='center'>没有相关数据</td></tr>";
                $("#ticktTable tbody").append(html);
                $("#baseForm ul").empty();//清空分页
            }
            JY.Model.loadingClose();
		}
	})
}
function preview(obj) {
    var url= window.URL.createObjectURL(obj.files[0]);
    $(obj).prev().attr("src",url);
    imgFile = obj.files[0];
}
function preview2(obj) {
    var url= window.URL.createObjectURL(obj.files[0]);
    $(obj).prev().attr("src",url);
    imgFile2 = obj.files[0];
}
//新增
function addClick(){
    clearData();
    JY.Model.edit("auForm_edit","新增商品",function(){
        var that=$(this);
        if(JY.Validate.form("generateForm")){
            if($(".shopImg").attr("src")==""+jypath+"/static/images/back/add_img.jpg"||$(".shopDeilImg").attr("src")==""+jypath+"/static/images/back/add_img.jpg"){
                JY.Model.info("请先上传图片!");
            }else{
                $(".masks").removeClass("hide");
                var obj={};
                obj.productName=$("#generateForm input[name='productName']").val().trim();
                obj.productNumber=$("#generateForm input[name='productNumber']").val().trim();
                obj.productDescribe=$(".des").val();
                obj.productType=$("#groom").find("option:selected").val();
                var productPrice=$("#generateForm input[name='productPrice']").val()*100;
                obj.productPrice=parseInt(productPrice);
                obj.productPoint=$("#generateForm input[name='productPoint']").val().trim();
                obj.state=$("#groomsSel").find("option:selected").val();
                obj.ondate=$("#generateForm input[name='ondate']").val();
                obj.offdate=$("#generateForm input[name='offdate']").val();
                obj.catId=parentIds;
                obj.sortOrder=$("#generateForm input[name='sortOrder']").val();
                ym.ajax({
                    url : "/shop/product/add",
                    type : "post",
                    param:{
                        "product":JSON.stringify(obj),
                    },
                    success : function(data) {
                        if(data.res==1){
                            var relevanceId=data.obj;
                            var formData=new FormData();
                            formData.append("imageFile",imgFile);
                            formData.append("imageFile2",imgFile2);
                            formData.append("relevanceId",relevanceId);
                            formData.append("relevanceTpyeId",10);
                            formData.append("relevanceTpyeDetail",1);
                            formData.append("relevanceTpyeDetail2",2);
                            $.ajax({
                                url: jypath + "/uploadVideoAndImage",
                                type: "post",
                                processData: false,
                                contentType: false,
                                data: formData,
                                success: function (data) {
                                    if(data.res==1){
                                        var imagePath=data.obj.imagePath;
                                        var imagePath2=data.obj.imagePath2;
                                        ym.ajax({
                                            url: "/shop/product/updatePic",
                                            type: "post",
                                            param:{
                                                "productId":relevanceId,
                                                "picPath":imagePath,
                                                "detPicPath":imagePath2,
                                            },
                                            data: formData,
                                            success: function (data) {
                                                JY.Model.loadingClose();
                                                if(data.res==1){
                                                    that.dialog("close");
                                                    $(".masks").addClass("hide");
                                                    JY.Model.info("操作成功!",function(){getUserList();});
                                                }else{
                                                    delFuc(relevanceId);
                                                }
                                            }
                                        })
                                    }else{
                                        that.dialog("close");
                                        $(".masks").addClass("hide");
                                        delFuc(relevanceId);
                                    }
                                }
                            })
                        }else{
                            that.dialog("close");
                        }
                    }
                })
            }

        }
    });
}
//删除
function delFuc(relevanceId){
    ym.ajax({
        url: "/shop/product/del",
        type: "post",
        param:{
            "productId":relevanceId,
        },
        data: formData,
        success: function (data) {

        }
    })
}
//编辑
function editClick(){
    clearData();
    var chks =[];
    var doctorId="";
    $('#ticktTable input[name="ids"]:checked').each(function(){
        chks.push($(this).val());
    });
    if(chks.length==0) {
        JY.Model.info("您没有选择任何内容!");
    }else if(chks.length==1){
        var obj=JSON.parse(chks);
        parentIds=obj.catId;
        $("#generateForm input[name='productName']").val(obj.productName);
        $("#generateForm input[name='productNumber']").val(obj.productNumber);
        $(".des").val(obj.productDescribe);
        $("#groom").find("option[value = '"+obj.productType+"']").prop("selected","selected");
        $("#groomsSel").find("option[value = '"+obj.state+"']").prop("selected","selected");
        var productPrice=(obj.productPrice*0.01).toFixed(2);
        $("#generateForm input[name='productPrice']").val(productPrice);
        $("#generateForm input[name='productPoint']").val(obj.productPoint);
        $("#generateForm input[name='ondate']").val(obj.onTimeString);
        $("#generateForm input[name='offdate']").val(obj.offTimeString);
        $(".shopImg").attr("src",obj.productPic);
        $(".shopDeilImg").attr("src",obj.productDetailsPic);
        $("#preResources").val(obj.name);
        $("#generateForm input[name='sortOrder']").val(obj.sortOrder);
        JY.Model.edit("auForm_edit","修改商品",function(){
            var that=$(this);
            var obj1={};
            obj1.productId=obj.productId;
            obj1.productName=$("#generateForm input[name='productName']").val().trim();
            obj1.productNumber=$("#generateForm input[name='productNumber']").val().trim();
            obj1.productDescribe=$(".des").val();
            obj1.productType=$("#groom").find("option:selected").val();
            var productPrice=$("#generateForm input[name='productPrice']").val().trim()*100;
            obj1.productPrice=parseInt(productPrice);
            obj1.productPoint=$("#generateForm input[name='productPoint']").val().trim();
            obj1.ondate=$("#generateForm input[name='ondate']").val();
            obj1.offdate=$("#generateForm input[name='offdate']").val();
            obj1.state=$("#groomsSel").find("option:selected").val();
            obj1.sortOrder=$("#generateForm input[name='sortOrder']").val().trim();
            obj1.catId=parentIds;
            JY.Model.loading();
            if(imgFile.name == undefined&&imgFile2.name==undefined){
                obj1.productPic;
                obj1.productDetailsPic;
                ym.ajax({
                    url : "/shop/product/update",
                    type : "post",
                    param:{
                        "product":JSON.stringify(obj1),
                    },
                    success : function(data) {
                        if(data.res==1){
                            JY.Model.loadingClose();
                            that.dialog("close");
                            JY.Model.info("操作成功!",function(){getUserList();});
                        }
                    }
                })
            }else{
                var formData=new FormData();
                if(imgFile.name!=undefined){
                    formData.append("imageFile",imgFile);
                    formData.append("relevanceTpyeDetail",1);
                }
                if(imgFile2.name!=undefined){
                    formData.append("imageFile2",imgFile2);
                    formData.append("relevanceTpyeDetail2",2);
                }
                formData.append("relevanceId",obj.productId);
                formData.append("relevanceTpyeId",10);
                $.ajax({
                    url : jypath + "/uploadVideoAndImage",
                    type : "post",
                    processData : false,
                    contentType : false,
                    data:formData,
                    success : function(data) {
                        if(data.res==1){
                            var imagePath=data.obj.imagePath;
                            var imagePath2=data.obj.imagePath2;
                            obj1.productPic=imagePath;
                            obj1.productDetailsPic=imagePath2;
                            ym.ajax({
                                url : "/shop/product/update",
                                type : "post",
                                param:{
                                    "product":JSON.stringify(obj1),
                                },
                                success : function(data) {
                                    if(data.res==1){
                                        JY.Model.loadingClose();
                                        that.dialog("close");
                                        JY.Model.info("操作成功!",function(){getUserList();});
                                    }
                                }
                            })
                        }
                    }
                })
            }
        });
    }else if(chks.length>1){
        JY.Model.info("一次只能编辑一条信息!");
    }
}
// 启用禁用
function enAbleClick(type){
    var chks =[];
    $('#ticktTable input[name="ids"]:checked').each(function(){
        var jsonV=$(this).val();
        chks.push(JSON.parse(jsonV));
    });
    if(chks.length==0) {
        JY.Model.info("您没有选择任何内容!");
    }else if(chks.length>0){
        var states="";
        if(type==1){
            //启用
            states=1;
        }else if(type==0){
            //禁用
            states=0;
        }
        var obj={};
        obj.state=states;
        obj.products=chks;
        JY.Model.message("auForm_edits","修改上下架",function(){
            var that = $(this);
            ym.ajax({
                url : "/shop/product/updateBatch",
                type : "post",
                param:{
                    "products":JSON.stringify(obj)
                },
                jsonType : "json",
                success : function(data) {
                    if(data.res==1){
                        that.dialog("close");
                        JY.Model.info("操作成功!",function(){getUserList();});
                    }
                }
            })
        });
    }
}
function clearData(){
    $("#generateForm input").val("");
    $("#generateForm textarea").val("");
    $("#groom").find("option[value = '1']").prop("selected","selected");
    $("#groomsSel").find("option[value = '1']").prop("selected","selected");
    $("#generateForm .shopImg").attr("src",""+jypath+"/static/images/back/add_img.jpg");
    $("#generateForm .shopDeilImg").attr("src",""+jypath+"/static/images/back/add_img.jpg");
    imgFile={};
    imgFile2={};
    $("#input1").val("");
    $("#input2").val("");
}
